package com.server.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.server.common.QueryPageParam;
import com.server.common.Result;
import com.server.entity.Browse;
import com.server.service.BrowseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/browse")
public class BrowseController {
	@Autowired
	private BrowseService browseService;

	@PostMapping("/saveORmodify")
	public Result saveORmodify(@RequestBody Browse browse){
		System.out.println(browse);
		if(browseService.saveOrUpdate(browse))
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}
	@PostMapping("/delete")
	public Result delete(@RequestBody Map<String, List<Integer>> requestMap){
		boolean res = true;
		List<Integer> ids = requestMap.get("ids");
		for(Integer id : ids){
			if(id!=null)
				res=res&browseService.removeById(id);
		}
		if(res)
			return Result.suc(null, 1L);
		else
			return Result.fail();
	}

	@PostMapping("/querylike")
	public Result querylike(@RequestBody QueryPageParam query) {
		// 创建分页对象
		Page<Browse> page = new Page<>(query.getPageNum(), query.getPageSize());

		// 获取查询参数
		HashMap<String, Object> map = query.getParam();

		// 创建条件构造器
		LambdaQueryWrapper<Browse> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		// 动态拼接条件
		String id = map.get("id") != null ? map.get("id").toString().trim() : "";
		String uid = map.get("uid") != null ? map.get("uid").toString().trim() : "";
		String gid = map.get("gid") != null ? map.get("gid").toString().trim() : "";
		String time = map.get("time") != null ? map.get("time").toString().trim() : "";
		if (!id.isEmpty()) {
			lambdaQueryWrapper.eq(Browse::getId, id);
		}
		if (!uid.isEmpty()) {
			lambdaQueryWrapper.like(Browse::getGid, uid);
		}
		if (!gid.isEmpty()) {
			lambdaQueryWrapper.like(Browse::getGid, gid); // 精确查询
		}
		if (!time.isEmpty()) {
			lambdaQueryWrapper.like(Browse::getTime, time); // 精确查询
		}

		// 执行查询
		IPage<Browse> res = browseService.pageC(page, lambdaQueryWrapper);
		// 返回结果
		return Result.suc(res.getRecords(), res.getTotal());
	}
}
